package cave.renderer;

import android.util.FloatMath;


public class Sprite {
	
	private float x, y;
	private float width, height;
	private Texture texture;
	private Animation animation;
	private Animation.Mode animationMode;
	private float animationTime;
	private float[] color = new float[4];
	private float[] orientation = new float[2];
	
	public void init(Texture texture, float x, float y, float width, float height) {
		reset();
		
		this.texture = texture;
		this.x = x;
		this.y = y;
		this.width = width;
		this.height = height;
		this.texture.incUsers();
	}
	
	public void init(Animation animation, Animation.Mode mode, float x, float y, float width, float height) {
		reset();
		
		this.animation = animation;
		this.animationMode = mode;
		this.x = x;
		this.y = y;
		this.width = width;
		this.height = height;
		this.animation.incUsers();
	}

	private void reset() {
		x = 0; y = 0;
		width = 0.5f; height = 0.5f;
		texture = null; animation = null;
		color[0] = 1; color[1] = 1; color[2] = 1; color[3] = 1;
		orientation[0] = 0; orientation[1] = 1;
		texture = null;
		animation = null;
		animationTime = 0;
	}
	
	public void updateAnimation(float dt) {
		if (animation != null) {
			this.animationTime += dt;
			texture = animation.getFrame(animationTime, animationMode);
		}
	}
	
	public void resetAnimation() {
		if (animation != null) {
			this.animationTime = 0;
			texture = animation.getFrame(animationTime, animationMode);
		}
	}
	
	public void setPosition(float x, float y) {
		this.x = x;
		this.y = y;
	}
	
	public void setX(float x) {
		this.x = x;
	}
	
	public void setY(float y) {
		this.y = y;
	}
	
	public float getX() {
		return x;
	}

	public float getY() {
		return y;
	}

	public float getWidth() {
		return width;
	}

	public float getHeight() {
		return height;
	}

	public void setColor(float r, float g, float b, float a) {
		color[0] = r; color[1] = g; color[2] = b; color[3] = a;
	}
	
	public float[] getColor() {
		return color;
	}

	public void setOrientation(float x, float y) {
		orientation[0] = x; orientation[1] = y;
	}
	
	public void setOrientation(float radians) {
		orientation[0] = FloatMath.cos(radians + (float)Math.PI/2);
		orientation[1] = FloatMath.sin(radians + (float)Math.PI/2);
	}
	
	public float[] getOrientation() {
		return orientation;
	}
	
	public Texture getTexture() {
		return texture;
	}

	public void freeTextures() {
		if (animation == null) {
			texture.decUsers();
		} else {
			animation.decUsers();
		}
	}

}
